package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.http.HttpResponse;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import org.springframework.http.HttpRequest;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //    1.判断路径是否需要拦截（静态资源和login界面不需要拦截）
        String requestURI = request.getRequestURI();
        String[] urls = {
                "/backend/**",
                "/front/**",
                "/employee/login",
                "/user/sendMsg",
                "/user/login",
        //        swapper
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };
        boolean flag = check(urls, requestURI);//有不能拦截的资源就返回true
        if(flag){
        //    释放资源
            filterChain.doFilter(request,response);
            return;
        }
        //    2.用户是否登录（判断session）
        Long employee = (Long) request.getSession().getAttribute("employee");

        if(employee!=null){
            //用户已登录
            BaseContext.setCurrentId(employee);
            filterChain.doFilter(request,response);
            return;
        }

        //    2.2用户是否登录（判断验证码）
        Long userId = (Long) request.getSession().getAttribute("user");
        if(userId!=null){
            //用户已登录
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(request,response);
            return;
        }
        //    3.用户未登录，和前端配合，响应code=0 && msg=NOTLOGIN给前端，前端调用方法来跳转到登录界面，后端不能进行跳转
        String jsonString = JSON.toJSONString(R.error("NOTLOGIN"));
        response.getWriter().write(jsonString);
        return;
    }

    private boolean check(String[] urls, String requestURI) {
        //路径匹配器
        AntPathMatcher pathMatcher = new AntPathMatcher();
        //遍历数组中的表达式
        for (String url : urls) {
            boolean match = pathMatcher.match(url, requestURI);
            if (match) return true;
        }
        return false;
    }


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }


    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
